package class04;

/**
 * <a href="https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/">剑指 Offer 51. 数组中的逆序对</a>
 */
public class Code03_ReversePair {
    public static int way1(int[] arr) {
        return process1(arr, 0, arr.length - 1);
    }

    private static int process1(int[] arr, int L, int R) {
        if (L == R) {
            return 0;
        }
        int M = L + ((R - L) >> 1);
        return process1(arr, L, M) + process1(arr, M + 1, R) + merge(arr, L, M, R);
    }

    private static int merge(int[] arr, int L, int M, int R) {
        int[] help = new int[R - L + 1];
        int i = help.length - 1, result = 0;
        int l = M, r = R;
        while (l >= L || r >= M + 1) {
            if (l < L) {
                help[i--] = arr[r--];
            } else if (r < M + 1) {
                help[i--] = arr[l--];
            } else {
                result += arr[l] > arr[r] ? r - M : 0;
                help[i--] = arr[l] > arr[r] ? arr[l--] : arr[r--];
            }
        }
        System.arraycopy(help, 0, arr, L, help.length);
        return result;
    }

    public static void main(String[] args) {
        int[] arr1 = {7, 5, 6, 4};
        System.out.println(way1(arr1));
    }
}
